//
//  BCWalletExchangeContentView.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2019/1/21.
//  Copyright © 2019 guoshikeji. All rights reserved.
//

#import "BCWalletExchangeContentView.h"

//
#import "UserWalletExchangeResponse.h"

//view
#import "BCWalletExchangeDirectionView.h"//兑换方向
#import "BCWalletExchangeInputDiplayView.h"
#import "BCWalletExchangeOutputDiplayView.h"

//选择兑换方向币种控制器
#import "BCWalletExchangeFromToController.h"


static NSString *ExplainProtoclLinkString = @"explain://";

//
static CGFloat BCWalletExchangeContentViewLeftPadding = 20.0;
//
static CGFloat BCWalletExchangeContentViewTopPadding = 15.0;
static CGFloat BCWalletExchangeContentViewDirectionPadding = 20.0;
static CGFloat BCWalletExchangeContentViewAmountPadding = 25.0;
static CGFloat BCWalletExchangeContentViewInputPadding = 12.0;
static CGFloat BCWalletExchangeContentViewAvailablePadding = 5.0;
static CGFloat BCWalletExchangeContentViewOutLabelPadding = 30.0;
static CGFloat BCWalletExchangeContentViewExplainPadding = 30.0;
static CGFloat BCWalletExchangeContentViewExplainTVPadding = 20.0;

@interface BCWalletExchangeContentView () <BCWalletExchangeInputDiplayViewDelegate,QMUITextViewDelegate>

/**
 兑换方向
 */
@property (nonatomic, strong) QMUILabel *directionLabel;
/**
 *兑换方向视图
 */
@property (nonatomic, strong) BCWalletExchangeDirectionView *direcitonView;
/**
 *兑换数量
 */
@property (nonatomic, strong) QMUILabel *exchangeAmountLabel;
/**
 *BCWalletExchangeDiplayView
 */
@property (nonatomic, strong) BCWalletExchangeInputDiplayView *exchangeInputView;
/**
 *availableLabel
 */
@property (nonatomic, strong) QMUILabel *availableLabel;

/**
 *exchangeOutLabel
 */
@property (nonatomic, strong) QMUILabel *exchangeOutLabel;
/**
 *BCWalletExchangeDiplayView
 */
@property (nonatomic, strong) BCWalletExchangeOutputDiplayView *exchangeOutputView;
/**
 *outputEqualLabel
 */
@property (nonatomic, strong) QMUILabel *outputEqualLabel;

/**
 *explainLabel
 */
@property (nonatomic, strong) QMUILabel *explainLabel;
//
/**
 *explainTV
 */
@property (nonatomic, strong) QMUITextView *explainTV;

@end

@implementation BCWalletExchangeContentView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setContentScroll];
    }
    return self;
}
- (void)setContentScroll {
    self.contentScroll = [UIScrollView new];
    self.contentScroll.showsVerticalScrollIndicator = false;
    [self addSubview:self.contentScroll];
    [self.contentScroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(self);
        make.width.height.mas_equalTo(self);
    }];
    //
    [self setupSubviews];
}
- (QMUILabel *)topTitleLabel {
    QMUILabel *label = [QMUILabel new];
    label.textColor = [UIColor qmui_colorWithHexString:@"#333333"];
    label.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
    label.numberOfLines = 0;
    return label;
}

- (void)setupSubviews {
    self.directionLabel = [self topTitleLabel];
    [self.contentScroll addSubview:self.directionLabel];
    [self.directionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentScroll).offset(BCWalletExchangeContentViewTopPadding);
        make.left.mas_equalTo(self.contentScroll).offset(BCWalletExchangeContentViewLeftPadding);
        make.width.mas_equalTo(self.contentScroll).offset(-BCWalletExchangeContentViewLeftPadding*2);
    }];
    //
    self.direcitonView = [BCWalletExchangeDirectionView new];
    [self.contentScroll addSubview:self.direcitonView];
    [self.direcitonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.directionLabel.mas_bottom).offset(BCWalletExchangeContentViewDirectionPadding);
        make.left.mas_equalTo(self.contentScroll).offset(BCWalletExchangeContentViewLeftPadding);
        make.width.mas_equalTo(self.contentScroll).offset(-BCWalletExchangeContentViewLeftPadding*2);
        make.height.mas_equalTo([BCWalletExchangeDirectionView defaultHeight]);
    }];
    [self.direcitonView.changeButton addTarget:self action:@selector(changeButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    [self.direcitonView.fromButton addTarget:self action:@selector(directionFromToButtonClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.direcitonView.toButton addTarget:self action:@selector(directionFromToButtonClickedAction:) forControlEvents:UIControlEventTouchUpInside];
    //
    self.exchangeAmountLabel = [self topTitleLabel];
    [self.contentScroll addSubview:self.exchangeAmountLabel];
    [self.exchangeAmountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.direcitonView.mas_bottom).offset(BCWalletExchangeContentViewAmountPadding);
        make.left.right.mas_equalTo(self.directionLabel);
    }];
    //
    self.exchangeInputView = [BCWalletExchangeInputDiplayView new];
    self.exchangeInputView.delegate = self;
    [self.contentScroll addSubview:self.exchangeInputView];
    [self.exchangeInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.exchangeAmountLabel.mas_bottom).offset(BCWalletExchangeContentViewInputPadding);
        make.left.mas_equalTo(self.contentScroll).offset(10.0);
        make.width.mas_equalTo(self.contentScroll).offset(-20.0);
        make.height.mas_equalTo([BCWalletExchangeInputDiplayView defaultHeight]);
    }];
    //
    self.availableLabel = [QMUILabel new];
    self.availableLabel.textColor = [UIColor qmui_colorWithHexString:@"#666666"];
    self.availableLabel.font = [UIFont systemFontOfSize:11 weight:UIFontWeightRegular];
    self.availableLabel.numberOfLines = 0;
    [self.contentScroll addSubview:self.availableLabel];
    [self.availableLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.exchangeInputView.mas_bottom).offset(BCWalletExchangeContentViewAvailablePadding);
        make.left.mas_equalTo(self.contentScroll).offset(BCWalletExchangeContentViewLeftPadding);
        make.width.mas_equalTo(self.contentScroll).offset(-BCWalletExchangeContentViewLeftPadding*2);
    }];
    //
    self.exchangeOutLabel = [self topTitleLabel];
    [self.contentScroll addSubview:self.exchangeOutLabel];
    [self.exchangeOutLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.availableLabel.mas_bottom).offset(BCWalletExchangeContentViewOutLabelPadding);
        make.left.right.mas_equalTo(self.directionLabel);
    }];
    //
    self.exchangeOutputView = [BCWalletExchangeOutputDiplayView new];
    [self.contentScroll addSubview:self.exchangeOutputView];
    [self.exchangeOutputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.exchangeOutLabel.mas_bottom).offset(BCWalletExchangeContentViewInputPadding);
        make.left.mas_equalTo(self.contentScroll).offset(10.0);
        make.width.mas_equalTo(self.contentScroll).offset(-20.0);
        make.height.mas_equalTo([BCWalletExchangeInputDiplayView defaultHeight]);
    }];
    //
    self.outputEqualLabel = [QMUILabel new];
    self.outputEqualLabel.textColor = self.availableLabel.textColor;
    self.outputEqualLabel.font = self.availableLabel.font;
    [self.contentScroll addSubview:self.outputEqualLabel];
    [self.outputEqualLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.availableLabel);
        make.right.mas_equalTo(self.availableLabel);
        make.top.mas_equalTo(self.exchangeOutputView.mas_bottom).offset(BCWalletExchangeContentViewAvailablePadding);
    }];
    //
    self.explainLabel = [self topTitleLabel];
    [self.contentScroll addSubview:self.explainLabel];
    [self.explainLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.directionLabel);
        make.top.mas_equalTo(self.outputEqualLabel.mas_bottom).offset(BCWalletExchangeContentViewExplainPadding);
    }];
    //
    self.explainTV = [QMUITextView new];
    self.explainTV.scrollEnabled = false;
    self.explainTV.editable = false;
    self.explainTV.delegate = self;
    self.explainTV.textContainerInset = UIEdgeInsetsZero;
    [self.contentScroll addSubview:self.explainTV];
    [self.explainTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.explainLabel.mas_bottom).offset(BCWalletExchangeContentViewExplainTVPadding);
        make.left.right.mas_equalTo(self.explainLabel);
    }];
    //
    self.explainTV.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor darkMainColor],
                                           NSUnderlineColorAttributeName: [UIColor darkMainColor],
                                           NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
}
//
- (void)setExchangeData:(UserWalletExchangeData *)exchangeData {
    _exchangeData = exchangeData;
    //
    self.directionLabel.text = exchangeData.flow.exchange_direction;
    //
    self.direcitonView.exchangeData = exchangeData;
    //
    self.exchangeAmountLabel.text = exchangeData.flow.exchange_amount;
    //
    self.exchangeOutLabel.text = exchangeData.flow.get_amount;
    //
    self.explainLabel.text = exchangeData.flow.agreement_title;
    //我已阅读并接受兑换说明内部所有条款
    NSString *explainD = exchangeData.flow.agreement.title?:@"";
    NSString *text = exchangeData.flow.agreement.text?:@"";
    NSString *explainTVString = [text stringByReplacingOccurrencesOfString:@"{}" withString:explainD];
    //
    NSMutableAttributedString *explainAttri = [[NSMutableAttributedString alloc] initWithString:explainTVString attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11 weight:UIFontWeightRegular],NSForegroundColorAttributeName:[UIColor qmui_colorWithHexString:@"#666666"]}];
    NSRange explainDRange = [explainTVString rangeOfString:explainD];
    if (explainDRange.location!=NSNotFound) {
        [explainAttri addAttribute:NSLinkAttributeName value:ExplainProtoclLinkString range:explainDRange];
    }
    self.explainTV.attributedText = explainAttri;
    [self.explainTV sizeToFit];
    //
    CGFloat height = self.explainTV.contentSize.height;
    [self.explainTV mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
}
- (void)setDataModel:(BCWalletExchangeDataModel *)dataModel {
    _dataModel = dataModel;
    //
    self.direcitonView.dataModel = dataModel;
    //
    if (dataModel.exchangeData) {
        self.exchangeData = dataModel.exchangeData;
    }
    //设置其他
    //兑换数量  单位  多少可用
    UserWalletExchangeDataCurrencyModel *fromCurrency = dataModel.fromCurrency;
    UserWalletExchangeDataCurrencyModel *toCurrency = dataModel.toCurrency;
    if (fromCurrency) {
        self.exchangeInputView.placeholder = dataModel.exchangeData.flow.input_exchange_amount;
        self.exchangeInputView.allTitle = dataModel.exchangeData.flow.all;
        //
        self.exchangeInputView.fromCurrency = fromCurrency;
        //
        NSString *do_amount = self.exchangeData.flow.do_amount;
        do_amount = [do_amount stringByReplacingOccurrencesOfString:@"{}" withString:fromCurrency.money];
        self.availableLabel.text = do_amount;
    }else {
        self.availableLabel.text = nil;
    }
    //
    if (toCurrency) {
        self.exchangeOutputView.toCurrency = toCurrency;
    }
    //1BTC≈3706.10USDT
    if (fromCurrency&&toCurrency) {
        NSString *one = @"1";
        CGFloat output = [self outputAmountFromInput:one];
        NSString *outString = [self number:output digits:toCurrency.scaler.length-1];
        self.outputEqualLabel.text = [NSString stringWithFormat:@"%@%@≈%@%@",one,fromCurrency.acronyms,outString,toCurrency.acronyms];
    }else {
        self.outputEqualLabel.text = nil;
    }
    //
    [self.contentScroll layoutIfNeeded];
    [self layoutContentScrollSize];
}
/**
 根据传出计算
 */
- (CGFloat)outputAmountFromInput:(NSString *)input {
    if (input.length) {
        UserWalletExchangeDataCurrencyModel *fromCurrency = self.dataModel.fromCurrency;
        UserWalletExchangeDataCurrencyModel *toCurrency = self.dataModel.toCurrency;
        if (fromCurrency&&toCurrency) {
            return input.floatValue*fromCurrency.central/toCurrency.central;
        }
        return 0;
    }
    return 0;
}
/**
 设置Scroll的contentSize
 */
- (void)layoutContentScrollSize {
    //计算整体高度
    CGFloat height = 0;
    //
    height += BCWalletExchangeContentViewTopPadding;
    height += CGRectGetHeight(self.directionLabel.frame);
    //
    height += BCWalletExchangeContentViewDirectionPadding;
    height += CGRectGetHeight(self.direcitonView.frame);
    //
    height += BCWalletExchangeContentViewAmountPadding;
    height += CGRectGetHeight(self.exchangeAmountLabel.frame);
    //
    height += BCWalletExchangeContentViewInputPadding;
    height += CGRectGetHeight(self.exchangeInputView.frame);
    //
    height += BCWalletExchangeContentViewAvailablePadding;
    height += CGRectGetHeight(self.availableLabel.frame);
    //
    height += BCWalletExchangeContentViewOutLabelPadding;
    height += CGRectGetHeight(self.exchangeOutLabel.frame);
    //
    height += BCWalletExchangeContentViewInputPadding;
    height += CGRectGetHeight(self.exchangeOutputView.frame);
    //
    height += BCWalletExchangeContentViewAvailablePadding;
    height += CGRectGetHeight(self.outputEqualLabel.frame);
    //
    height += BCWalletExchangeContentViewExplainPadding;
    height += CGRectGetHeight(self.explainLabel.frame);
    //
    height += BCWalletExchangeContentViewExplainTVPadding;
    height += CGRectGetHeight(self.explainTV.frame);
    //
    height += 20.0;
    self.contentScroll.contentSize = CGSizeMake(0, height);
}

/**
 获取兑换金额
 */
- (NSString *)exchangeAmount {
    NSString *amount = self.exchangeInputView.inputTF.text;
    if (!amount.length) {
        [self.exchangeInputView.inputTF becomeFirstResponder];
    }
    return amount;
}

- (void)clearInput {
    //
    self.exchangeInputView.inputTF.text = nil;
}


#pragma mark -changeButtonDidClickedAction
- (void)changeButtonDidClickedAction {
    UserWalletExchangeDataCurrencyModel *fromCurrency = self.dataModel.fromCurrency;
    UserWalletExchangeDataCurrencyModel *toCurrency = self.dataModel.toCurrency;
    if (fromCurrency&&toCurrency) {
        self.dataModel.fromCurrency = toCurrency;
        self.dataModel.toCurrency = fromCurrency;
        //
        self.dataModel = _dataModel;
        self.exchangeInputView.inputTF.text = nil;
    }
}

#pragma mark - directionFromToButtonClickedAction:
- (void)directionFromToButtonClickedAction:(id)sender {
    WEAK_SELF
    [BCWalletExchangeFromToController showFromController:self.fromController data:self.dataModel complete:^(UserWalletExchangeDataCurrencyModel * _Nonnull from, UserWalletExchangeDataCurrencyModel * _Nonnull to) {
        if (from&&to) {
            if ([from.cur_id isEqualToString:wself.dataModel.fromCurrency.cur_id]&&[to.cur_id isEqualToString:wself.dataModel.toCurrency.cur_id]) {//和以前一样
                //不操作
            }else {
                wself.dataModel.fromCurrency = from;
                wself.dataModel.toCurrency = to;
                //
                wself.dataModel = wself.dataModel;
                wself.exchangeInputView.inputTF.text = nil;
            }
        }
    }];
    
}

#pragma mark - QMUITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([URL.absoluteString isEqualToString:ExplainProtoclLinkString]) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(walletExchangeContentViewExplainAction)]) {
            [self.delegate walletExchangeContentViewExplainAction];
        }
        return false;
    }
    return YES;
}


#pragma mark - BCWalletExchangeInputDiplayViewDelegate
- (void)walletExchangeInputAmountTextChanged:(NSString *)text {
    UserWalletExchangeDataCurrencyModel *fromCurrency = self.dataModel.fromCurrency;
    UserWalletExchangeDataCurrencyModel *toCurrency = self.dataModel.toCurrency;
    NSString *outString = nil;
    if (fromCurrency&&toCurrency) {
        if (text.length) {
            CGFloat output = [self outputAmountFromInput:text];
            outString = [self number:output digits:toCurrency.scaler.length-1];
        }
    }
    self.exchangeOutputView.inputTF.text = outString;
}



- (NSString *)number:(CGFloat)number digits:(NSInteger)digits {
    switch (digits) {
        case 0:
            return [NSString stringWithFormat:@"%.0f",number];
            break;
        case 1:
            return [NSString stringWithFormat:@"%.1f",number];
            break;
        case 2:
            return [NSString stringWithFormat:@"%.2f",number];
            break;
        case 3:
            return [NSString stringWithFormat:@"%.3f",number];
            break;
        case 4:
            return [NSString stringWithFormat:@"%.4f",number];
            break;
        case 5:
            return [NSString stringWithFormat:@"%.5f",number];
            break;
        case 6:
            return [NSString stringWithFormat:@"%.6f",number];
            break;
        case 7:
            return [NSString stringWithFormat:@"%.7f",number];
            break;
        case 8:
            return [NSString stringWithFormat:@"%.8f",number];
            break;
        case 9:
            return [NSString stringWithFormat:@"%.9f",number];
            break;
        default:
            return [NSString stringWithFormat:@"%.10f",number];
            break;
    }
}

@end
